<template>
  <view class="author-home">
    <u-popup
      v-model="show"
      mode="center"
      :closeable="false"
      close-icon-color="#888"
      border-radius="16"
      @close="close"
      z-index="9"
      width="600"
    >
      <view class="author-home-popup">
        <view class="title">{{ title }}</view>
        <view class="form-container">
          <u-form :model="authorHomeForm" ref="uForm" label-width="150">
            <u-form-item label="主页昵称" prop="name" :border-bottom="false">
              <u-input
                v-model="authorHomeForm.name"
                maxlength="6"
                border
                placeholder="请输入主页昵称(最大长度6)"
              />
            </u-form-item>
            <u-form-item
              v-if="show"
              label="设置头像"
              prop="avatar"
              :border-bottom="false"
            >
              <image
                :src="authorHomeForm.avatar"
                mode="aspectFill"
                class="author-avatar"
              />
              <view class="upload-right">
                <view @click="handleRandom" class="avatar-btn"
                  >随机更改头像</view
                >

                <view
                  @click="handleUploadAvatar"
                  class="slot-btn"
                  hover-class="slot-btn__hover"
                  hover-stay-time="150"
                  >自定义上传</view
                >
                <!-- <Upload
									ref="uUpload"
									:action="uploadParams.action"
									:header="{
										'Authorization': 'Bearer ' + token // token
									}"
									:custom-btn="true"
									height="200"
									upload-text="选择"
									:limitType="uploadParams.limitType"
									:source-type="['album']"
									:max-count="uploadParams.maxCount"
									:type="uploadParams.uploadType"
									:show-upload-list="false"
									del-bg-color="#56d39d"
									:auto-upload="true"
									:file-list="uploadParams.fileList"
									@on-remove="removeImage"
									@on-uploaded="uploadSuccess">
									<view slot="addBtn" class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
										自定义上传
									</view>
								</Upload> -->
              </view>
            </u-form-item>
            <u-form-item
              v-if="authorHomeForm.id === ''"
              label="页面口令"
              prop="code"
              :border-bottom="false"
            >
              <u-input
                v-model="authorHomeForm.code"
                maxlength="8"
                border
                placeholder="请输入页面口令"
              ></u-input>
              <u-button
                slot="right"
                size="mini"
                type="primary"
                hover-class="none"
                :custom-style="{
                  backgroundColor: '#56d39d',
                }"
                @click="handleCheckCode"
                >检测</u-button
              >
            </u-form-item>
            <!-- 显示定制 -->
            <u-form-item
              v-if="appletType === '1'"
              label="主页类型"
              prop="show_make"
              :border-bottom="false"
            >
              <u-radio-group
                v-model="authorHomeForm.show_make"
                active-color="#56d39d"
                :disabled="authorHomeForm.id > 0"
              >
                <u-radio name="2">定制</u-radio>
                <!-- <u-radio name="1">图库</u-radio> -->
              </u-radio-group>
            </u-form-item>
            <view style="color:red">
                <view>说明: 以上图库和定制分别表示达人收益方式</view>
                <view>图库：收益来源于用户看广告+会员收益</view>
                <view>定制：收益来源于用户定制付费订单收益</view>
              </view>
          </u-form>

          <!-- 温馨提示 -->
          <view v-if="authorHomeForm.id" class="update-tips">
            修改主页会导致资料重新审核，有一定的时间口令搜索不到该主页，请慎重操作。
          </view>
          <view class="btn-container">
            <u-button class="btn" plain hover-class="none" @click="show = false"
              >取消</u-button
            >
            <u-button
              class="btn"
              type="primary"
              hover-class="none"
              :custom-style="{
                backgroundColor: '#56d39d',
              }"
              @click="sumbit"
              :loading="btnLoading"
              >确认</u-button
            >
          </view>
        </view>
        <!-- 删除主页 -->
        <view
          v-if="authorHomeForm.id"
          class="delete-home"
          @click="handleDeleteAuthorHome"
        >
          <text class="huiju-iconfont huiju-icon-shanchu"></text>
          <text class="bottom-view-button-text">删除主页</text>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { mapGetters } from "vuex";
import Upload from "@/components/upload/upload";
import config from "@/utils/config";
import {
  checkCode,
  createAuthorHomeInfo,
  merchantAuthorEdit,
  merchantAuthorDelete,
} from "@/api/artworks";
import { checkText } from "@/utils/index";
export default {
  components: {
    Upload,
  },
  props: {
    popupShow: {
      type: Boolean,
      default: false,
    },
    popupTitle: {
      type: String,
      default: "",
    },
    authorHomeInfo: {
      type: Object,
      default: () => {
        return {};
      },
    },
    showMake: {
      type: String,
      default: "2",
    },
  },
  data() {
    return {
      show: this.popupShow,
      title: this.popupTitle,
      authorHomeInfoData: this.authorHomeInfo,
      btnLoading: false,
      appletType: config.appletType,
      authorHomeForm: {
        id: "",
        name: "",
        avatar: "https://design-aliyun.tsgzs.com/author-default-avatar/1.jpg",
        code: "",
        show_make: this.showMake || "2",
      },
      uploadParams: {
        limitType: ["png", "PNG", "jpg", "JPG", "jpeg", "webp"],
        maxCount: 1,
        uploadType: "image",
        action: `${config.baseApi}/client/upload/uploadImg`,
        fileList: [],
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入主页昵称",
            trigger: ["change", "blur"],
          },
        ],
        code: [
          {
            required: true,
            message: "请输入页面口令",
            trigger: ["change", "blur"],
          },
        ],
        avatar: [
          {
            required: true,
            message: "请上传头像",
            trigger: ["change", "blur"],
          },
        ],
      },
      randomNum: 1,
    };
  },
  computed: {
    ...mapGetters(["token"]),
  },
  watch: {
    popupShow: {
      immediate: true,
      handler(val, oldValue) {
        this.show = val;
        if (val) {
          this.handleRandom();
          this.$nextTick(() => {
            this.$refs.uForm.setRules(this.rules);
          });
        }
      },
    },
    popupTitle: {
      immediate: true,
      handler(val, oldValue) {
        this.title = val;
      },
    },
    authorHomeInfo: {
      immediate: true,
      handler(val, oldValue) {
        if (val) {
          this.authorHomeForm.name = val.name;
          this.authorHomeForm.avatar = val.avatar;
          this.authorHomeForm.show_make = val.show_make;
          this.uploadParams.fileList = [
            {
              url: val.avatar,
            },
          ];
          this.authorHomeForm.id = val.id;
        } else {
          this.uploadParams.fileList = [];
        }
      },
    },
  },
  methods: {
    // 随机头像
    handleRandom() {
      let randomNum = this.randomNumFn(1, 66);
      this.authorHomeForm.avatar = `https://design-aliyun.tsgzs.com/author-default-avatar/${randomNum}.jpg`;
      this.randomNum = randomNum;
    },

    randomNumFn(min, max) {
      let choices = max - min + 1;
      return Math.floor(Math.random() * choices + min);
    },

    // 上传头像
    handleUploadAvatar() {
      let that = this;
      uni.chooseImage({
        count: 1,
        success: (res) => {
          let temp = res.tempFilePaths[0];
          uni.uploadFile({
            url: `${config.baseApi}/client/upload/uploadImg`,
            filePath: temp,
            name: "file",
            header: {
              Authorization: "Bearer " + that.token, // token
            },
            success: (imgRes) => {
              let result = JSON.parse(imgRes.data);
              if (result.code === 200 && result.data) {
                //开始检测
                that.authorHomeForm.avatar = result.data.cover_path;
                uni.showToast({
                  icon: "none",
                  title: "上传成功！",
                });
              } else {
                uni.hideLoading();
                uni.showToast({
                  icon: "none",
                  title: "上传失败，请重试",
                });
              }
            },
            fail: function (e) {
              console.log(e);
            },
          });
        },
        fail(e) {
          console.log(e);
        },
      });
    },

    // 删除主页
    handleDeleteAuthorHome() {
      uni.showModal({
        title: "确认删除",
        content: `确定删除“${this.authorHomeForm.name}”主页吗？删除后该主页下的所有图片会一并删除并不可再继续推广。`,
        confirmText: "确定",
        cancelText: "取消",
        confirmColor: "#56d39d",
        success: ({ confirm, cancel }) => {
          if (confirm) {
            merchantAuthorDelete({
              id: this.authorHomeForm.id,
            }).then((result) => {
              if (result && result.code === 200) {
                this.show = false;
                uni.showToast({
                  title: "删除成功",
                  icon: "none",
                });
                this.$emit("success");
              } else {
                uni.showToast({
                  title: "删除成功，请重试",
                  icon: "none",
                });
              }
            });
          }
        },
      });
    },

    // 确定提交
    sumbit() {
      this.$refs.uForm.validate(async (valid) => {
        if (valid) {
          // 检查文本内容
          const flag = await checkText(this.authorHomeForm.name);

          // 更新主页信息
          if (this.authorHomeForm.id) {
            this.merchantAuthorEditFn();
            return;
          }

          // 新增校验
          if (!/^[\da-z]+$/i.test(this.authorHomeForm.code)) {
            uni.showToast({
              title: "口令仅支持数字或字母组合",
              icon: "none",
            });
            return;
          }

          // 判断是否上传了头像
          this.createAuthorHomeInfoFn();
        } else {
          console.log("验证失败");
        }
      });
    },

    // 修改更新主页信息
    merchantAuthorEditFn() {
      this.btnLoading = true;
      uni.showToast({
        title: "创建中...",
        icon: "loading",
        mask: true,
      });
      const { id, name, avatar, show_make } = this.authorHomeForm;
      merchantAuthorEdit({ id, name, avatar, show_make })
        .then((result) => {
          this.btnLoading = false;
          if (result && result.code === 200) {
            this.show = false;
            uni.showToast({
              title: "修改成功",
              icon: "none",
            });
            this.$emit("success");
          } else {
            uni.showToast({
              title: "修改失败，请重试",
              icon: "none",
            });
          }
        })
        .catch(() => {
          this.btnLoading = false;
        });
    },

    // 添加
    createAuthorHomeInfoFn() {
      this.btnLoading = true;
      uni.showToast({
        title: "创建中...",
        icon: "loading",
        mask: true,
      });
      createAuthorHomeInfo(this.authorHomeForm)
        .then((result) => {
          this.btnLoading = false;
          if (result && result.code === 200) {
            this.show = false;
            uni.showToast({
              title: "创建成功",
              icon: "none",
            });
            this.$emit("success");
          } else {
            uni.showToast({
              title: "创建失败，请重试",
              icon: "none",
            });
          }
        })
        .catch(() => {
          this.btnLoading = false;
        });
    },

    // 上传成功
    uploadSuccess(data) {
      let avatar = "";
      data.forEach((item) => {
        avatar = item.response.data.cover_path;
        return;
      });
      this.authorHomeForm.avatar = avatar;
    },

    // 检测口令是否可用
    handleCheckCode() {
      if (!this.authorHomeForm.code) {
        uni.showToast({
          title: "页面口令不能为空！",
          icon: "none",
          mask: false,
        });
        return;
      }
      // 新增校验
      if (!/^[\da-z]+$/i.test(this.authorHomeForm.code)) {
        uni.showToast({
          title: "口令仅支持数字或字母组合",
          icon: "none",
        });
        return;
      }
      uni.showToast({
        title: "检测中...",
        icon: "loading",
        mask: true,
      });
      checkCode({
        code: this.authorHomeForm.code,
      }).then((result) => {
        console.log(result);
        if (result && !result.data) {
          uni.showToast({
            title: "恭喜你，该口令可用",
            icon: "none",
          });
        } else {
          uni.showToast({
            title: "口令已存在或不可用，请重新输入",
            icon: "none",
          });
        }
      });
    },

    // 删除图片
    removeImage() {
      this.authorHomeForm.avatar = "";
    },

    // 关闭
    close() {
      this.authorHomeForm.name = "";
      this.authorHomeForm.code = "";
      this.authorHomeForm.id = "";
      this.authorHomeForm.avatar = "";
      this.uploadParams.fileList = [];
      this.$emit("close", false);
    },
  },
};
</script>
<style lang="scss" scoped>
.author-home-popup {
  position: relative;
  padding: 32rpx;

  .title {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 32rpx;
  }

  .btn-container {
    display: flex;
    padding-top: 32rpx;
    justify-content: space-between;

    .btn {
      flex: 1;
    }
    .btn:nth-child(1) {
      margin-right: 24rpx;
    }
  }

  .delete-home {
    position: absolute;
    width: 140rpx;
    height: 44rpx;
    line-height: 44rpx;
    right: 32rpx;
    top: 32rpx;
    color: $uni-color-primary2;
    font-size: 24rpx;
    text-align: right;
  }
}
.update-tips {
  font-size: 20rpx;
  color: #f35252;
}

.author-avatar {
  width: 148rpx;
  height: 148rpx;
  border-radius: 50%;
  border: 2rpx solid #eaeaea;
  display: block;
}

.upload-right {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  width: 200rpx;
  margin-left: 24rpx;

  .avatar-btn {
    margin-bottom: 28rpx;
  }

  .avatar-btn,
  .slot-btn {
    background: #e0eefc;
    color: $uni-color-primary;
    padding: 0 12rpx;
    width: 180rpx;
    height: 48rpx;
    line-height: 48rpx;
    font-size: 24rpx;
    text-align: center;
    border-radius: 8rpx;
  }
}
</style>
